package com.dcits.electronic_account.service.impl;

import com.dcits.electronic_account.bean.Flow;
import com.dcits.electronic_account.bean.VirtualAccount;
import com.dcits.electronic_account.mapper.RechargeMapper;
import com.dcits.electronic_account.mapper.TransferAccountsMapper;
import com.dcits.electronic_account.service.TransferAccountsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: YHC
 * @Date: 2022/6/25
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class TransferAccountsServiceImpl implements TransferAccountsService {

    @Resource
    TransferAccountsMapper transferAccountsMapper;

    @Resource
    RechargeMapper rechargeMapper;

    @Override
    public VirtualAccount searchVirById(Integer virId) {
        return rechargeMapper.searchVirByUserId(virId);
    }

    @Override
    public VirtualAccount searchVirByUserName(String userName) {
        return transferAccountsMapper.searchVirByUserName(userName);
    }

    @Override
    public VirtualAccount searchVirByPhone(String virPhone) {
        VirtualAccount virtualAccount = transferAccountsMapper.searchVirByPhone(virPhone);
        return virtualAccount;
    }

    @Override
    public void transfer(BigDecimal amount, VirtualAccount payer, VirtualAccount payee) {
        Flow flow = new Flow();
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        flow.setTime(dateFormat.format(date));
        flow.setAmount(amount);
        flow.setPayer(payer.getUserId().toString());
        flow.setPayee(payee.getUserId().toString());
        flow.setType(2);
        if(transferAccountsMapper.updateBalance(payer.getBalance().subtract(amount), payer.getPhone())<1) throw new RuntimeException("更改金额sql语句失败");
        if(transferAccountsMapper.updateBalance(payee.getBalance().add(amount), payee.getPhone())<1) throw new RuntimeException("更改金额sql语句失败");
        if(transferAccountsMapper.addFlow(flow)<1) throw new RuntimeException("添加流水失败");
    }
}
